package com.jh.microservice.reactive;

import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.GenericApplicationContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SpringEventDemo {

    public static void main(String[] args) {

        /*GenericApplicationContext context = new GenericApplicationContext();
        context.addApplicationListener(event -> {
            System.out.printf("【线程：%s】event：%s\n", Thread.currentThread().getName(), event);
        });
        context.refresh();
        context.publishEvent("Hello World");
        context.close();*/

        // 默认同步非阻塞
        SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
        // 构建线程池（使用了线程池就是异步的）
        ExecutorService executor = Executors.newSingleThreadExecutor();
        multicaster.setTaskExecutor(executor);
        // 事件监听
        multicaster.addApplicationListener(event -> {
            System.out.printf("【线程：%s】event：%s\n", Thread.currentThread().getName(), event);
        });
        // 发布事件
        multicaster.multicastEvent(new PayloadApplicationEvent<>("Hello World", "Hello World"));
        executor.shutdown();

    }

}
